import { LoginApi, RegisterApi } from '@/api';
import React, { useState } from 'react';
import './index.less';
import img from '@/assets/images/logo.png';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import { useNavigate } from 'react-router-dom';
import { useToast } from '@/utils/toast';

export default function Login() {
  let [isLogin, setIsLogin] = useState(true);
  let [userName, setUserName] = useState('13250340627');
  let [password, setPassWord] = useState('wolfcode123');
  let navigate = useNavigate();
  let toast = useToast();
  // 点击登录/注册按钮
  let btnClick = () => {
    isLogin ? login() : register();
  };
  // 抽离出来的登录逻辑
  const login = () => {
    LoginApi({
      password: password,
      username: userName,
    }).then((res) => {
      // console.log(res);
      // HomeApi();
      if (res.errCode === 0) {
        // console.log(res);
        toast('success', '登录成功');
        // 保存token值
        localStorage.setItem('token', res.data);
        // 跳到首页
        navigate('/home');
      }
    });
  };
  // 抽离出来的注册逻辑
  const register = () => {
    RegisterApi({
      password: password,
      phone: userName,
    }).then((res) => {
      if (res.errCode === 0) {
        // console.log(res);
        toast('success', '注册成功');
        setIsLogin(true);
      }
    });
  };
  return (
    <div className="LoginBox">
      <img src={img} alt="" className="logo" />
      <div className="LoginFrom">
        <TextField
          variant="outlined"
          placeholder="请输入手机号"
          value={userName}
          onChange={(e) => setUserName(e.target.value)}
        />
        <TextField
          variant="outlined"
          type="password"
          placeholder="请输入密码"
          value={password}
          onChange={(e) => setPassWord(e.target.value)}
        />
        <Button variant="contained" onClick={btnClick}>
          {isLogin ? '登录' : '注册'}
        </Button>
      </div>
      <div className="form_bottom">
        <span onClick={() => setIsLogin(!isLogin)} className="register">
          {isLogin ? '去注册' : '去登录'}
        </span>
        <span className="gotoHome">返回首页</span>
      </div>
    </div>
  );
}
